import 'dart:html';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:my_flutter_test/reqs/requests.dart';
import 'package:my_flutter_test/states/userState.dart';
import 'package:my_flutter_test/utils.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();
  bool registering = false;


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (ctx) => UserState(),
      builder: (context, child) => Container(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            Container(
              width: 360,
              height: 360,
              child: ClipOval(
                child:  Image.asset('assets/img/cxk.jpg')
              ),
            ),
            Form(
              key: _formKey, //设置globalKey，用于后面获取FormState
              autovalidateMode: AutovalidateMode.onUserInteraction,
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 28.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: ElevatedButton(
                            child: Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: registering
                                  ? const CircularProgressIndicator()
                                  : const Text("注册"),
                            ),
                            onPressed: () {
                              // 通过_formKey.currentState 获取FormState后，
                              // 调用validate()方法校验用户名密码是否合法，校验
                              // 通过后再提交数据。
                              if (!registering &&
                                  (_formKey.currentState as FormState)
                                      .validate()) {
                                //验证通过提交数据
                                requestLogin(_unameController.text,
                                    _pwdController.text)
                                    .then((value) {
                                      //print('here');
                                  Provider.of<UserState>(context, listen: false).user = value;
                                  Navigator.pop(context);
                                }).onError((error, stackTrace) {
                                  print(error);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(
                                      content: Text('登录失败！'),
                                    ),
                                  );
                                  setState(() {
                                    registering = false;
                                  });
                                });
                                setState(() {
                                  registering = true;
                                });
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  TextFormField(
                    autofocus: true,
                    controller: _unameController,
                    decoration: InputDecoration(
                      labelText: "用户名",
                      hintText: "用户名或邮箱",
                      icon: Icon(Icons.person),
                    ),
                    // 校验用户名
                    validator: (v) {
                      return v!.trim().isNotEmpty ? null : "用户名不能为空";
                    },
                  ),
                  // 登录按钮
                  TextFormField(
                    controller: _pwdController,
                    decoration: InputDecoration(
                      labelText: "密码",
                      hintText: "您的登录密码",
                      icon: Icon(Icons.lock),
                    ),
                    obscureText: true,
                    //校验密码
                    validator: (v) {
                      var reg =
                      RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,15}$');
                      return reg.hasMatch(v!.trim()) ? null : "密码8-15位,包含数字字母";
                    },
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
